<template>
    <div class="selectTreeClass">

        <el-select
            v-model="mineStatusLabel"
            :disabled="depStatus"
            placeholder="请选择部门"
            clearable
            multiple
            collapse-tags
            @clear="clearableFn"
            @remove-tag="remove"
            ref="selectRef"
            filterable :filter-method="filterMethod"
        >
            <div style="position: relative;height: 40px;">
                <div style="position: absolute;left: 20px;">
                    <el-button @click="emit" size="small" >
                        确定
                    </el-button>
                    <el-button  @click="cancle" size="small">
                        取消子选项
                    </el-button>
                    <el-button @click="clearableFn" size="small">
                        清空
                    </el-button>
                </div>
            </div>

            <el-option :value="mineStatusValue" style="height: auto">
                <el-tree
                    show-checkbox
                    node-key="deptCode"
                    :default-expand-all="true"
                    :default-checked-keys="defaultCheckedKeys"
                    :expand-on-click-node="false"
                    :data="treeData"
                    :check-strictly="true"
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                    ref="treeRef"
                    @check="handleCheckChange"
                    @check-change="checkChange"
                    @node-click="nodeClick"
                    
            ></el-tree>
            </el-option>
        </el-select>
    </div>
</template>
  
  <script>
  import {getTreeFramedepartmentList} from '@/api/system.js'
export default {
    name: 'selectTreeCom',
    components: {},
    model: {
        prop: 'value',
        event: 'change'
    },
    props:{
        value:{
            type: String,
        },
        isAll:{
            type: Boolean,
            default: false
        },
        depStatus:{
            type: Boolean,
            default: false
        },
    },
    data() {
        return {
            treeData:[],
            defaultProps: {
                children: 'children',
                label: 'deptName',
                id: 'deptCode',
            },
            mineStatusLabel: [],
            mineStatusValue: [],

            rowCancelObj: null,
            defaultCheckedKeys: null,
        }
    },
    mounted(){
        this.getTree();
    },
    methods: {
        getTree(){
            getTreeFramedepartmentList(this.isAll).then(({data})=>{
                this.treeData = [data] // 
                this.transName(this.value)
            })
        },
        transName(){
            let arrIds = [];
            try {
                if(this.value){
                    arrIds  =  this.value.split(',');
                }
            } catch (error) {
                
            }
            this.defaultCheckedKeys = arrIds // 树的
            this.idToObj(arrIds);
        },
        // tree节点过滤
        filterNode(value, data) {
            if (!value) return true
            return data.deptName.indexOf(value) !== -1
        },
        filterMethod(value) {
            this.$refs.treeRef.filter(value)
        },
        emit(){
            let ids = this.mineStatusValue.map(item=>item.deptCode).join(',')
            this.$emit('selected',ids)
            this.$emit('change',ids)
            this.$refs.selectRef.blur()
        },
        cancle() {
            if (this.rowCancelObj) {
                let arr = this.diguiTree(this.rowCancelObj)

                arr.forEach(item=>{
                    this.$refs.treeRef.setChecked(item,false)

                    let indexVal =    this.mineStatusValue.findIndex(obj=>obj.deptCode == item)
                    if(indexVal != -1){
                        this.mineStatusValue.splice(indexVal,1)
                        this.mineStatusLabel.splice(indexVal,1)
                    }
                })
            }
        },

        nodeClick(data1) {
            this.rowCancelObj = data1.children
        },
        handleCheckChange() {
            let res = this.$refs.treeRef.getCheckedNodes();
            let arrLabel = [];
            let arr = [];
            res.forEach(item => {
                arrLabel.push(item.deptName);
                arr.push(item);
            });
            this.mineStatusValue = arr;
            this.mineStatusLabel = arrLabel;
        },
        checkChange(data1, selfStatus, data3) {
            // 1. 选中父 ,全选子.
            if (selfStatus === true) {
                let arr = this.digui(data1)
                arr.forEach(item=>{
                    this.$refs.treeRef.setChecked(item,true,true)
                })
            }else{
                let arr = this.digui(data1)
                arr.forEach(item=>{
                    this.$refs.treeRef.setChecked(item,false)
                })
            }

        },
        idToObj(ids){
            this.mineStatusValue = []
            this.mineStatusLabel = []
            ids.forEach(id=>{
               let obj =  this.treeSearchObj(id);
               this.mineStatusValue.push(obj);
               this.mineStatusLabel.push(obj.deptName);
            })
        },  
        treeSearchObj(id){
            function findNodeById(tree, id) {
                if (!tree || !Array.isArray(tree)) {
                    return null;
                }
                
                for (const node of tree) {
                    if (node.deptCode === id) {
                        return node; // 返回匹配的节点
                    }
                    
                    if (node.children && node.children.length) {
                        const foundNode = findNodeById(node.children, id); // 递归搜索子节点
                        if (foundNode) {
                            return foundNode; // 若找到匹配的节点，则返回节点
                        }
                    }
                }
                
                return {}; // 若未找到匹配的节点，返回 null
            }
            return  findNodeById(this.treeData,id)
        },  
        digui(obj) {
            let newArr = []

            function di(obj) {
                newArr.push(obj.deptCode)
                obj.children &&
                    obj.children.length > 0 &&
                    obj.children.forEach((item) => di(item))
            }

            newArr.push(obj.deptCode)
            obj.children &&
                obj.children.length > 0 &&
                obj.children.forEach((item) => di(item))
            return newArr
        },
        diguiTree(arr) {
            let newArr = []
            function di(obj) {
                newArr.push(obj.deptCode)
                obj.children &&
                    obj.children.length > 0 &&
                    obj.children.forEach((item) => di(item))
            }
            arr.forEach((item) => di(item))
            return newArr
        },
        //当多选时候，删除小标签时，将删除的子节点状态改为未勾选
        remove(val) {
            let selectNodes = this.$refs.treeRef.getCheckedNodes();
            for(let i = 0;i < this.$refs.treeRef.getCheckedNodes().length;i++){
                if(selectNodes[i].deptName == val){
                    let arrIds = this.digui(selectNodes[i])
                    arrIds&& arrIds.forEach((item,ind)=>{
                        this.$refs.treeRef.setChecked( arrIds[ind] , false,true)
                        let indexVal =    this.mineStatusValue.findIndex(obj=>obj.deptCode == item)
                        if(indexVal != -1){
                            this.mineStatusValue.splice(indexVal,1)
                            this.mineStatusLabel.splice(indexVal,1)
                        }
                    })
                }
            }
            
        },
        //清除所有选项
        clearableFn() {
            this.$refs.treeRef.setCheckedKeys([])
            this.mineStatusValue = []
            this.mineStatusLabel = []
        },
    },
    watch:{
        'value'(newV){
            console.log(newV);
            if(newV){
                this.getTree();
            }
        }
    }
}
</script>
  
<style lang = "scss" scoped>
    :deep .el-input {
        width: 300px;
    }
    ::v-deep .el-tag.el-tag--info .el-tag__close{
        display: none;
    }

</style>

<style lang="scss">

.el-select-dropdown.is-multiple .el-select-dropdown__item {
    padding-right: 20 !important;
}
.el-select-dropdown__item.hover{
    background-color: transparent;
}
</style>
  